<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { dateFormatStr } from '../../../common/utils/normalUtils'

const emit = defineEmits(['update:modelValue', 'change'])
  const props = defineProps({
    modelValue: {
      type: [String, Array]
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd' // yyyy-MM-dd HH:mm:ss
    },
    changeData: {
      type: Boolean,
      default: false
    }
  })
const state:any = reactive({
  dateValue: null,
  value: ''
})

/**
 * 初始化日期
 * @param val
 */
const initValue = (val:any) => {
  state.value = val
  if (val) {
    if (Array.isArray(val))state.dateValue = val.map((item) => new Date(item))
    else state.dateValue = new Date(val)
  }
}

/**
 * 变化处理
 */
const changeHandler = () => {
  if (state.dateValue) {
    if (Array.isArray(state.dateValue)) {
      state.value = state.dateValue.map((item:any) => {
        return dateFormatStr(item, props.format)
      })
    } else state.value = dateFormatStr(state.dateValue, props.format)
  }
  state.value = dateFormatStr(state.dateValue, props.format)
  emit('update:modelValue', state.value)
  emit('change', props.changeData ? state.dateValue : state.value)
}

watch(() => props.modelValue, (val:any) => {
  initValue(val)
})

onMounted(() => {
  initValue(props.modelValue)
})

</script>

<template>
  <el-date-picker v-model="state.dateValue"
                  @change="changeHandler" />
</template>

<style scoped lang="scss">

</style>
